/**
 * Copyright (C) 2002-2006 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.kingcore.director.main;
 

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Observable;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.TabbedPaneUI;
import javax.swing.plaf.synth.PlainTabbedPaneUI;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import org.apache.log4j.Logger;

import wzw.beans.DbBean;
import wzw.manager.LanguageManager;
import wzw.swing.StatusBar;
import wzw.swing.event.LanguageChangeListener;
import wzw.util.ComponentUtil;
import wzw.util.I18nUtil;
import wzw.util.I18nUtils;
import wzw.util.StringUtils;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.base.ui.DirectorFrame;
import com.kingcore.director.base.ui.DirectorPanel;
import com.kingcore.director.book.ui.NoteBookMainPanel;
import com.kingcore.director.calendar.ui.CalendarMainPanel;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.core.util.Lunar;
import com.kingcore.director.note.ui.NotePaperMainPanel;
import com.kingcore.director.reminder.clock.Timer;
import com.kingcore.director.reminder.ui.ReminderMainPanel;
import com.kingcore.director.resourcemaster.ui.ResourceMasterMainPanel;
import com.kingcore.director.search.ui.LocalSearchMainPanel;
import com.kingcore.director.setting.encoding.StringEncoding;

/**
 * <p>director application main GUI file. </p>
 * @author	WUZEWEN on 2005-10-21
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @see		Object#hashCode()
 * @see		HashMap
 * @since	JDK5
 */ 
 
public class MainFrame extends DirectorFrame 
	implements ActionListener,
				MouseListener,
				LanguageChangeListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static String language = DirectorConstants.System_Language_CN; 
	public static String lookAndFeel = "Windows"; 
	
	private JPanel mainContentPane = null;
	private static Logger log=Logger.getLogger(MainFrame.class);
	Timer timer =null;
	public static String User_Data_Path="director.userdata.path";
	public static String Direcotr_Home="director.home.path";
	public static String Director_Language="director.language";
	
	
	public int clientTop = 1 ;
	public int clientHeight = 340 ;

	private LanguageManager languageManager =null;
	public LanguageManager getLanguageManager() {
		return languageManager;
	}

	public void setLanguageManager(LanguageManager languageManager) {
		this.languageManager = languageManager;
	}

	private StringEncoding se = null;
	
	//图片文件常量	
	public static final String appIco = "./resource/director.gif";
	public static final String appTrayIco = "./resource/director_tray.gif";
	public static final String pic_new = "./resource/new_awoke.gif";
	public static final String pic_mod = "./resource/mod_awoke.gif";
	public static final String pic_exit = "./resource/exit_sys.gif";
	
	public static final String pic_fileExplorer = "./resource/fileExplorer.gif";
	public static final String pic_fileCopy = "./resource/fileCopy.gif";
	public static final String pic_favoriteFile = "./resource/favoriteFile.gif";
	public static final String pic_programLibrary = "./resource/programLibrary.gif";
	public static final String pic_documentLibrary = "./resource/documentLibrary.gif";
	
	public static final String fLogin = ".\\..\\image\\login.gif";
	public static final String fExit = ".\\..\\image\\exit.gif";
	public static final String fCut = ".\\..\\image\\cut.gif";
	public static final String fCopy = ".\\..\\image\\copy.gif";
	public static final String fPaste = ".\\..\\image\\paste.gif";
	public static final String fDelete = ".\\..\\image\\delete.gif";
	public static final String fFlow = ".\\..\\image\\flow.gif";
	public static final String fPoint = ".\\..\\image\\point.gif";
	public static final String fRefresh = ".\\..\\image\\refresh.gif";
	public static final String fZoomIn = ".\\..\\image\\zoomin.gif";
	public static final String fZoomOut = ".\\..\\image\\zoomout.gif";
	public static final String fCheck = ".\\..\\image\\check.gif";
	public static final String fHelp = ".\\..\\image\\help.gif";
	public static final String fAbout = ".\\..\\image\\about.gif";

	public static final String tree_00 = "./resource/new_awoke.gif";
	public static final String tree_0000 = "./resource/copy_awoke.gif";
	public static final String tree_0001 = "./resource/exit_sys.gif";	
	public static final String tree_0002 = "./resource/director.gif";
	public static final String tree_0003 = "./resource/copy_awoke.gif";
	public static final String tree_0004 = "./resource/exit_sys.gif";	
	public static final String tree_0005 = "./resource/director.gif";
	
	public static final String tree_99 = "./resource/new_awoke.gif";

	private JTabbedPane mainTabPane;
	private LocalSearchMainPanel localSearchMainPanel;
	private CalendarMainPanel calendarMainPanel;
	private ResourceMasterMainPanel resourceMasterMainPanel;
	
	public StatusBar statusBar = null;
	private JToolBar toolBar = null ; //MainFrame和MainPanel都可以有自己的toolBar

	// main tabpane tab index
	public static int MainTabPane_ReminderMainPanel_Index = 0;
	public static int MainTabPane_CalendarMainPanel_Index = 1;
	public static int MainTabPane_ResourceMasterMainPanel_Index = 2;
	public static int MainTabPane_LocalSearchMainPanel_Index = 3;
	public static int MainTabPane_NoteBookMainPanel_Index = 4;  //取消
	public static int MainTabPane_NotePaperMainPanel_Index = 4;

	public final static int MainTabPane_FileExplorer_Index = 0;
	public final static int MainTabPane_FileCopy_Index = 1;
	public final static int MainTabPane_FavoriteFiles_Index = 2;
	public final static int MainTabPane_ProgramLibrary_Index = 3;
	public final static int MainTabPane_DocumentLibrary_Index = 4;
	
	public static String Default_Current_Panel = "FavoriteFiles";
	public static String[][] MainPanel_Codes = new String[][]{
						new String[]{"ReminderMainPanel","My Reminder"}
						,new String[]{"CalendarMainPanel","Calendar"}
						,new String[]{"FileExplorer","File Explorer"}
						,new String[]{"FileCopy","File Copy"}
						,new String[]{"FavoriteFiles","Favorite Files"}
						,new String[]{"ProgramLibrary","Programe Library"}
						,new String[]{"DocumentLibrary","Document Library"}
						,new String[]{"LocalSearchMainPanel","Local Search"}
						//,new String[]{"NoteBookMainPanel","NoteBook"} //先取消
						,new String[]{"NotePaperMainPanel","NotePaper"}
						};
	
	/** 
	 * @param args
	 */
	public static void main(String[] args) {
		
		System.out.println(MainFrame.class);
		
		double[] rates = {2d/5, 1d/5, 1d/5, 1d/5 };
		for (int i = 0; i < rates.length; i++) {
			System.out.println(rates[i]);
		}
		
	}
	
	//增加默认打开的Panel选择。
	//System_Default_Open_Panel = "FavoriteFilesMainPanel";
	public void openPanel(String panelName){
		//最开始刷新一下，解决OpenSwing的StatusBar的刷新显示问题
		DirectorComponentUtils.touchAllTabs( getMainTabbedPane() );
		DirectorComponentUtils.touchAllTabs( getResourceMasterMainPanel().getMainTabbedPane() );
		
		//定位到默认的：
		if (panelName.equals(MainPanel_Codes[0][0])) {
			this.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_ReminderMainPanel_Index );
			
		} else if (panelName.equals(MainPanel_Codes[1][0])) {
			this.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_CalendarMainPanel_Index );	

		} else if (panelName.equals(MainPanel_Codes[2][0])) {
			DirectorComponentUtils.openTabpage( this.getMainTabbedPane(), MainFrame.MainTabPane_ResourceMasterMainPanel_Index );
			DirectorComponentUtils.openTabpage( this.getResourceMasterMainPanel().getMainTabbedPane(), ResourceMasterMainPanel.MainTabPane_FileExplorer_Index );

		} else if (panelName.equals(MainPanel_Codes[3][0])) {
			DirectorComponentUtils.openTabpage( this.getMainTabbedPane(), MainFrame.MainTabPane_ResourceMasterMainPanel_Index );
			DirectorComponentUtils.openTabpage( this.getResourceMasterMainPanel().getMainTabbedPane(), ResourceMasterMainPanel.MainTabPane_FileCopy_Index );

		} else if (panelName.equals(MainPanel_Codes[4][0])) {
			DirectorComponentUtils.openTabpage( this.getMainTabbedPane(), MainFrame.MainTabPane_ResourceMasterMainPanel_Index );
			DirectorComponentUtils.openTabpage( this.getResourceMasterMainPanel().getMainTabbedPane(), ResourceMasterMainPanel.MainTabPane_FavoriteFiles_Index );

		} else if (panelName.equals(MainPanel_Codes[5][0])) {
			DirectorComponentUtils.openTabpage( this.getMainTabbedPane(), MainFrame.MainTabPane_ResourceMasterMainPanel_Index );
			DirectorComponentUtils.openTabpage( this.getResourceMasterMainPanel().getMainTabbedPane(), ResourceMasterMainPanel.MainTabPane_ProgramLibrary_Index);

		} else if (panelName.equals(MainPanel_Codes[6][0])) {
			DirectorComponentUtils.openTabpage( this.getMainTabbedPane(), MainFrame.MainTabPane_ResourceMasterMainPanel_Index );
			DirectorComponentUtils.openTabpage( this.getResourceMasterMainPanel().getMainTabbedPane(), ResourceMasterMainPanel.MainTabPane_DocumentLibrary_Index );

		} else if (panelName.equals(MainPanel_Codes[7][0])) {
			this.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_LocalSearchMainPanel_Index );	

		} else if (panelName.equals(MainPanel_Codes[8][0])) {
			this.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_NoteBookMainPanel_Index );	

		} else if (panelName.equals(MainPanel_Codes[9][0])) {

		}
	}

	
	/**
	 * This is the default constructor
	 * @throws Exception 
	 */
	private MainFrame() {
		// mainFrame 初始
		super();
		
		String str_width  = null;
		String str_height = null;
		try{
			languageManager = new LanguageManager();
			languageManager.addObserver( this );
	
			//step:set size of mainFrame
			String sql = "SELECT VAL FROM "+DirectorConstants.SYS_Setting  +
						" Where KEY='"+DirectorConstants.MainFrame_Size_Width+"'";
			DbBean dbBean = new DbBean();
			str_width  = dbBean.queryForString(sql);
			sql = "SELECT VAL FROM "+DirectorConstants.SYS_Setting  +
						" Where KEY='"+DirectorConstants.MainFrame_Size_Height+"'";
			str_height = dbBean.queryForString(sql);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if (str_width!=null && str_height!=null) {
			try{
				int i_width = Integer.parseInt(str_width);
				int i_height = Integer.parseInt(str_height);
				this.setSize(i_width, i_height);
			}catch(Exception ex){
				log.info("error value for MainFrame_Size_Width or Height, set to normal size.");
				ComponentUtil.setSizeToNormal(this);
			}
		}else{
			ComponentUtil.setSizeToNormal(this);
		}
		ComponentUtil.setLocationToCenter(this);

		Main.MainFrame_Size_Width = this.getSize().width;
		Main.MainFrame_Size_Height = this.getSize().height;
//		DirectorContext.setMainFrameWidth(this.getSize().width);
//		DirectorContext.setMainFrameHeight(this.getSize().height); //frame.getHeight());
		
		//step:initialize interface
		initializeInterface();
		
		// intiSystemTray();
	}

	private TrayPopupMenu trayPopupMenu = null;
    private TrayIcon trayIcon = null;  
    public void intiSystemTray(){
        if(SystemTray.isSupported()){ //检查当前系统是否支持系统托盘
             SystemTray tray = SystemTray.getSystemTray();//获取表示桌面托盘区的 SystemTray 实例。
             Image image  = Toolkit.getDefaultToolkit().getImage( appTrayIco );
             trayPopupMenu = new TrayPopupMenu(this); 
             this.getLanguageManager().addObserver(trayPopupMenu);
             //jdk6下 mouseEntered不支持，故这里设置tooltip
             trayIcon = new TrayIcon(image, null,  trayPopupMenu); 
             updateTrayIconToolTip(trayIcon);
             trayIcon.setImageAutoSize(true);
             trayIcon.addMouseListener(this);
             try{   
                  tray.add(trayIcon);  // 将 TrayIcon 添加到 SystemTray。 
             } catch   (AWTException   e)     {   
                  System.err.println(e);   
             }
        }else{
            System.out.println("你的系统不支持系统托盘");
        }
         
    }


    public void hideSystemTray(){
        if(SystemTray.isSupported()){ //检查当前系统是否支持系统托盘
             SystemTray tray = SystemTray.getSystemTray();//获取表示桌面托盘区的 SystemTray 实例。
             tray.remove(trayIcon);
        }else{ 
            System.out.println("你的系统不支持系统托盘");
        }
         
    }
    private void updateTrayIconToolTip(TrayIcon trayIcon) {
    	StringBuffer tooltip = new StringBuffer();
    	StringBuffer sb_lunar = new StringBuffer();
        Calendar calendar=Calendar.getInstance();
        Lunar lunar = new Lunar(calendar);
        if( this.trayIconDateMsg.indexOf("${lunar}")>-1 ){
        	sb_lunar.append("农历")
	        		.append(lunar.get_month())
	        		.append("月")
	        		.append(lunar.get_date())
	        		.append("(月")
	        		.append(lunar.get_Big_Or_Small())
	        		.append(")");
	    }

        //使用前替换
        this.trayIconDateMsg = StringUtils.replace(this.trayIconDateMsg, "${lunar}", sb_lunar.toString());
        this.trayIconDateMsg = StringUtils.replace(this.trayIconDateMsg, "${weekNumber}", calendar.get(Calendar.WEEK_OF_YEAR)+"");
        this.trayIconOpenMsg = StringUtils.replace(this.trayIconOpenMsg, "${hotKeyString}", Main.MainFrame_Shortcut_Key);
        tooltip.append( this.appIconTitle ).append(" - ");
        tooltip.append( trayIconDateMsg ).append(" ");
        tooltip.append( trayIconOpenMsg );
        trayIcon.setToolTip(tooltip.toString());
    }

    private void showMainFrame(boolean visable){
        this.setVisible(visable);
        if(this.isVisible() != visable)
           	System.out.println("222"+visable);
            this.setVisible(visable);
    }
    
	// These methods do not appear to be called at all when a JFrame
    // is being resized.
    @Override
    public void setSize(int width, int height) {
        //System.out.println("setSize");
        super.setSize(width, height);
    }

//    @Override   java.lang.StackOverflowError
//    public void setBounds(int x, int y, int width, int height) {
//        System.out.println("setBounds B");
//        
//        super.setSize(width, height);
//    }

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initializeInterface() {
		//this.setSize(800, 600);   
		//this.setBounds(0,0,800,600);

		this.setExtendedState(Frame.NORMAL);
		this.setContentPane(getMainContentPane());
		//this.setContentPane(getMainTabPane());
		this.setTitle("系统管家");
		this.setIconImage(Toolkit.getDefaultToolkit().createImage(appIco));

		//this.setResizable(false);
		//this.show() ;
		this.setForeground(Color.black);
		//this.setLocale(new java.util.Locale("zh", "CN", ""));
		this.setResizable(true);
		

		/// this.setJMenuBar(getMainMenu());
		
//		//this.thisResized(null);
//		this.addComponentListener(new java.awt.event.ComponentAdapter() {
//			public void componentResized(java.awt.event.ComponentEvent e) {
//				thisResized(e);
//            	statusBarResize();  //call StatusBar resize
//			}
//		});
		
		//this.setSize(800, 600);

		update(null,null);
		
//        this.addComponentListener(new ComponentAdapter() {
//            public void componentResized(ComponentEvent e) {
//                // This is only called when the user releases the mouse button.
//                //System.out.println("componentResized");
//            	//getMainContentPane().getComponent(3);
//            	//System.out.println("-------------resize 1");
//            	statusBarResize();  //call StatusBar resize
//            }
//        });
	}

	/**
	 * 自定义UI组件对象
	 */
	private TabbedPaneUI tabbedPaneUI = null;
	private TabbedPaneUI getTabbedPaneUI() {
		if (this.tabbedPaneUI==null) {
			this.tabbedPaneUI = new PlainTabbedPaneUI(28, -2); //加大Tab选项宽度，减小高度
		}
		return this.tabbedPaneUI;
	}
	
//	private boolean isResourceMasterMainPanelAdded=false;
//	private boolean isLocalSearchMainPanelAdded=false;
	public JTabbedPane getMainTabbedPane() {
		if (mainTabPane == null) {
			mainTabPane = new JTabbedPane();
			if ( ComponentUtil.getNimbusLookAndFeelClassName().equals(
					UIManager.getLookAndFeel().getClass().getName() )  ) {
				mainTabPane.setUI(getTabbedPaneUI());
			}
			
			mainTabPane.setBounds(new java.awt.Rectangle(13,7,461,298));
			mainTabPane.setTabPlacement(JTabbedPane.TOP);// 设定选项卡放在上部
			mainTabPane.addTab(" My Reminder   ", DirectorComponentUtils.createImageIcon("./resource/tree_00.gif"), getReminderMainPanel(), null); //new JPanel()
			mainTabPane.addTab(" My Calendar   ", DirectorComponentUtils.createImageIcon("./resource/calendar.gif"), getCalendarMainPanel(), null);  //getCalendarMainPanel()
			mainTabPane.addTab(" Resource Master   ", DirectorComponentUtils.createImageIcon("./resource/resourceMaster.gif"), getResourceMasterMainPanel(), null);  //getFileMasterMainPanel()
			mainTabPane.addTab(" Local Search ", DirectorComponentUtils.createImageIcon("./resource/my_search.gif"), getLocalSearchMainPanel(), null); //
			//mainTabPane.addTab(" My NoteBook  ", DirectorComponentUtils.createImageIcon("./resource/noteBook.gif"), getNoteBookMainPanel(), null);  //先取消使用
			mainTabPane.addTab(" My NotePaper  ", DirectorComponentUtils.createImageIcon("./resource/notePaper.gif"), getNotePaperMainPanel(), null);
			mainTabPane.setSelectedIndex( MainFrame.MainTabPane_ReminderMainPanel_Index );		
			//mainTabPane.addTab("高级动作设置", null, getAdvanced(), null);
			currentPanel = getReminderMainPanel();
			
			mainTabPane.addChangeListener(new javax.swing.event.ChangeListener() {
	            public void stateChanged(javax.swing.event.ChangeEvent e) {
	            	JTabbedPane   tabbedPane   =   (JTabbedPane)e.getSource();
	                int   selectedIndex   =   tabbedPane.getSelectedIndex(); 
               		log.info("tab stateChanged!");
               		// following code is delay loading.
	               	if(selectedIndex== MainTabPane_ReminderMainPanel_Index
	               			&& reminderMainPanel==null ){
	               		log.info("init reminderMainPanel");
	               		mainTabPane.setComponentAt(MainTabPane_ReminderMainPanel_Index, getReminderMainPanel()); 
	               	
	               	}else if(selectedIndex== MainTabPane_CalendarMainPanel_Index
	               			&& calendarMainPanel==null ){
	               		log.info("init calendarMainPanel");
	               		mainTabPane.setComponentAt(MainTabPane_CalendarMainPanel_Index, getCalendarMainPanel()); 
	               	
	               	}else if(selectedIndex== MainTabPane_ResourceMasterMainPanel_Index
	               			&& resourceMasterMainPanel==null ){ //有些情况下先创建了对象，但并没有加入到界面上去。
	               		log.info("init resourceMasterMainPanel");
	               		mainTabPane.setComponentAt(MainTabPane_ResourceMasterMainPanel_Index, getResourceMasterMainPanel()); 
	               		//isResourceMasterMainPanelAdded = true;
	                		
	               	}else if(selectedIndex== MainTabPane_LocalSearchMainPanel_Index
	               			&& localSearchMainPanel==null ){
	               		log.info("init localSearchMainPanel");
	               		//isLocalSearchMainPanelAdded = true;
	               		mainTabPane.setComponentAt(MainTabPane_LocalSearchMainPanel_Index, getLocalSearchMainPanel()); 
	               	
//	               	}else if(selectedIndex== MainTabPane_NoteBookMainPanel_Index
//	               			&& noteBookMainPanel==null ){
//	               		log.info("init NoteBookMainPanel");
//	               		mainTabPane.setComponentAt(MainTabPane_NoteBookMainPanel_Index, getNoteBookMainPanel()); 
	               	
	               	}else if(selectedIndex== MainTabPane_NotePaperMainPanel_Index
	               			&& notePaperMainPanel==null ){
	               		log.info("init NotePaperMainPanel");
	               		mainTabPane.setComponentAt(MainTabPane_NotePaperMainPanel_Index, getNotePaperMainPanel()); 
	               	
	               	}
	               	
	               	//System.out.println(selectedIndex + " "+mainTabPane.getSelectedComponent().getClass().toString());
	               	currentPanel = (DirectorPanel) mainTabPane.getSelectedComponent();
	               	currentPanel.refreshView();
	               	
	            }
	        });

		}
		return mainTabPane;
	}

	private NoteBookMainPanel noteBookMainPanel = null;
	private JPanel getNoteBookMainPanel() {
		if (noteBookMainPanel==null) {
			noteBookMainPanel = new NoteBookMainPanel(this);
			this.getLanguageManager().addObserver(noteBookMainPanel);
		}
		return noteBookMainPanel;
	}
	
	private NotePaperMainPanel notePaperMainPanel = null;
	private JPanel getNotePaperMainPanel() {
		if (notePaperMainPanel==null) {
			notePaperMainPanel = new NotePaperMainPanel(this);
			this.getLanguageManager().addObserver(notePaperMainPanel);
		}
		return notePaperMainPanel;
	}
	/**
	 * <p>this is local search main panel</p>
	 * @author Zeven on 2011-2-21
	 * @return
	 */
	public LocalSearchMainPanel getLocalSearchMainPanel() {
		if (localSearchMainPanel==null) {
			localSearchMainPanel = new LocalSearchMainPanel(this);
			this.getLanguageManager().addObserver(localSearchMainPanel);
		}
		return localSearchMainPanel;
	}
	
	public ResourceMasterMainPanel getResourceMasterMainPanel() {
		if (resourceMasterMainPanel==null) {
			resourceMasterMainPanel = new ResourceMasterMainPanel(this);
			this.getLanguageManager().addObserver(resourceMasterMainPanel);
		}
		return resourceMasterMainPanel;
	}
	
	
	private Component getCalendarMainPanel() {
		if (calendarMainPanel==null) {
			calendarMainPanel = new CalendarMainPanel(this);
			this.getLanguageManager().addObserver(calendarMainPanel);
		}
		return calendarMainPanel;
	}

    private boolean isFirstTime = true;
    /**
	 * override parent method.
	 * 
	 * @author WZWEN on 2006-04-28
	 */
    protected void processWindowEvent(WindowEvent e) {
        if ( (e.getID() == WindowEvent.WINDOW_CLOSING && DirectorConstants.System_CloseAction_Minimize.equals(DirectorConstants.System_CloseAction_Value) )
        		|| e.getID() == WindowEvent.WINDOW_ICONIFIED ) {
            int state = this.getExtendedState();	 
	        // Clear the maximized bits
	        state &= ~Frame.MAXIMIZED_BOTH;
	        // Minimize the frame	
	        //this.setExtendedState(ICONIFIED);
	        this.setVisible(false);
	        if(isFirstTime){
	            this.trayIconOneTimeMsg = StringUtils.replace(this.trayIconOneTimeMsg, "${hotKeyString}", Main.MainFrame_Shortcut_Key);
	            this.trayIcon.displayMessage(null, trayIconOneTimeMsg, TrayIcon.MessageType.INFO);
				isFirstTime = false;
	        }
	        //executeExitSystem();	
	        return ;
        }else if(e.getID() == WindowEvent.WINDOW_CLOSING && DirectorConstants.System_CloseAction_Close.equals(DirectorConstants.System_CloseAction_Value) ){
        	System.exit(0);
        	return ;
        }
        super.processWindowEvent(e);
    }
    
//	/**
//	 * 
//	 * @param e
//	 */
//	public void thisResized(java.awt.event.ComponentEvent e){
//		int width=new Double(leftScrollPanel.getParent().getSize().getWidth()).intValue();
//		int height=new Double(leftScrollPanel.getParent().getSize().getHeight()).intValue()-5;	//5=toolBar's height
//		//System.out.println("w="+width+" h="+height);
//
//		// 5=toolBar's height    2=距左右边界宽度     1=组件相互之间的宽度
//		leftScrollPanel.setBounds(new java.awt.Rectangle(2,this.clientTop,150, height) );
//		//centerBar.setBounds(new java.awt.Rectangle(150 +2+1, this.clientTop,4, height) );
//		rightScrollPanel.setBounds(new java.awt.Rectangle(150+2+1 +4,this.clientTop,width -(150+2+1 +4) -2, height));
//
//		
//		leftScrollPanel.setViewportView(getTree());
//		rightScrollPanel.setViewportView(getTable());
//	}
	
	
//	/**
//	 * 主菜单
//	 * @return
//	 */
//	private JMenuBar getMainMenu() {}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	public JPanel getMainContentPane() {
		if (mainContentPane == null) {
			mainContentPane = new JPanel();
			mainContentPane.setLayout(new BorderLayout());

			//上下分别是 ToolBar,StatusBar;
			//中间可以是所有的Container对象，如：
			//						JSplitPane(分隔面板容器)
			//						JDesktopPane(多文档面板容器)
			//						JPanel(普通面板容器)
			/// mainContentPane.add(getToolBar(), java.awt.BorderLayout.NORTH);
			//mainContentPane.add(getMainPanel(), java.awt.BorderLayout.CENTER);
			mainContentPane.add(getMainTabbedPane(), java.awt.BorderLayout.CENTER);
			
			//设置状态栏-》移动到每个Panel下面。
			//mainContentPane.add(getStatusBar(), java.awt.BorderLayout.SOUTH);
			
		}
		return mainContentPane;
	}

	/**
	 * @deprecated 放到每个MainPanel，每个MainPanel设置自己的ToolBar
	 *    Frame[ToolBar + MainPanel[MainContent]*n + StatusBar] 替换为：
	 *  ->Frame[MainPanle[ToolBar + MainContent + StatusBar]*n]  
	 * @param toolBar
	 */
	public void setToolBar(JToolBar toolBar){
//		this.toolBar = toolBar;
//		DirectorPanel t_currentPanel = (DirectorPanel) mainTabPane.getSelectedComponent();
//		if(t_currentPanel!=null)
//			t_currentPanel.add(toolBar, java.awt.BorderLayout.NORTH);
//		mainContentPane.add(toolBar, java.awt.BorderLayout.NORTH);
	}
	
	public JToolBar getToolBar(){
		return this.toolBar;
	}

	private ReminderMainPanel reminderMainPanel = null;
	/**
	 * 
	 * @return container Object
	 */
	public ReminderMainPanel getReminderMainPanel() {

		if (reminderMainPanel==null) {
			reminderMainPanel = new ReminderMainPanel(this);
			this.getLanguageManager().addObserver(reminderMainPanel);
		}
		return reminderMainPanel;
	}

//	private static double[] StatusBar_Item_Width_Rates={2d/5, 1d/5, 1d/5, 1d/10, 1d/10};
//	private static String[] StatusBar_Item_Text={"就绪", "系统管家", "泽文堂出品", "", ""};

	
//	/**
//	 * return current status bar object.
//	 * @return
//	 */
//	public StatusBar getStatusBar() {
//		if (statusBar == null) {
//			statusBar = createStatusBar();
//			//this.getLanguageManager().addObserver(statusBar);
//		}
//		return statusBar;
//	}
//
//	/**
//	 * create a new status bar if needed.
//	 * @return
//	 */
//	private StatusBar createStatusBar() {
//		statusBar = new StatusBar();
//		//statusBar.setEditable(false);
//		int width = this.getWidth();  //DirectorContext.getMainFrameWidth();
//		double[] rates = StatusBar_Item_Width_Rates;
//		String[] txts = StatusBar_Item_Text;
//		
//		for (int i = 0; i < StatusBar_Item_Width_Rates.length; i++) {
//			statusBar.addStatusCell((int)(width*rates[i])); 
//			statusBar.setStatus(i, txts[i]);
//		}
////			statusBar.addStatusCell(width*2/5); //200);
////			statusBar.addStatusCell(width*1/5); //150);
////			statusBar.addStatusCell(width*1/5); //150);
////			statusBar.addStatusCell(width*1/5); //180);
////			statusBar.setStatus(0,"就绪");
////			statusBar.setStatus(1,"系统管家");
////			statusBar.setStatus(2,"泽文堂出品");
////			statusBar.setStatus(3,"");
//		return statusBar;
//	}
	
//	private void statusBarResize(){
//		
////		int width = this.getWidth();  
////		double[] rates = StatusBar_Item_Width_Rates;
////
////		StatusBar l_statusBar = getStatusBar();
////		int cellCount = l_statusBar.getCellCount();
////		JLabel[] label = new JLabel[cellCount];
////		String[] txts = new String[cellCount];
////		for (int i = 0; i < cellCount; i++) {
////			//System.out.println("width new="+width+"cellCount"+i);
////			txts[i] = l_statusBar.getStatusText(i);
//////			label[i]  = l_statusBar.getLabel(i);
//////			System.out.println( label[i].getPreferredSize().getWidth() );
//////			int w = (int)(width*rates[i]);
//////			label[i].setPreferredSize(new Dimension(w, getPreferredSize().height));
//////			label.getPreferredSize().setSize(width*rates[i], getPreferredSize().height);
//////			System.out.println( w+"  "+label[i].getPreferredSize().getWidth()
//////					  + " "+label[i].getText() );
////		}
//////		this.getStatusBar().revalidate();		
////		statusBar = new StatusBar();  // refer to new object.
//		
//		//if size changed,create a new status bar
//		StatusBar oldStatusBar = this.getStatusBar();
//		mainContentPane.remove(this.getStatusBar());  //remove before add a new one.
//		mainContentPane.add( createStatusBar() , java.awt.BorderLayout.SOUTH);
//		statusBar = this.getStatusBar();
//		int cellCount = statusBar.getCellCount();
//		for (int i = 0; i < cellCount; i++) {
//			statusBar.setStatus(i, oldStatusBar.getStatusText(i) );
//		}
//		//mainContentPane.remove(2);
//		
//		//mainContentPane.repaint();
//		
//		mainContentPane.revalidate();
//		
//	}
	
//	/**
//	 * 
//	 * @return
//	 */
//	private JToolBar getToolBar() {
//		// 工具条
//		if(toolBar==null){
//			toolBar = new JToolBar("Tool Bar"); // 工具栏
//			
//
//			 tb_creatAwoke = toolBar.add(new ButtonAction(MainFrame.pic_new));
//			 tb_creatAwoke.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_creatAwoke.setToolTipText("创建新的提醒");
//			 tb_creatAwoke.addActionListener( this );
//			 //toolBar.addSeparator();
//			 tb_modAwoke = toolBar.add(new ButtonAction(MainFrame.pic_mod));
//			 tb_modAwoke.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_modAwoke.setToolTipText("修改当前提醒");
//			 tb_modAwoke.addActionListener(this);
//
//			 // JToolBar中加入 JToggleButton的问题是显示很小。
//			 //toolBar.setLayout(new FlowLayout());
//			 //toolBar.addSeparator();
//			 j20 = new JToggleButton("AAAAA");
//			 j20.setText("AAAAA");
//			 //j20.setIcon( new ImageIcon(MainFrame.pic_exit) );
//			 j20.setAction( getShowToolBarAction() );
//			 //j20.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 //toolBar.add(j20);
//
//			 //toolBar.addSeparator();
//			 j21 = new JToggleButton("Status",new ImageIcon(MainFrame.pic_exit) );
//			 //j21.setText("Status");
//			 //j21.setIcon( new ImageIcon(MainFrame.pic_exit) );
//			 j21.setAction( getShowStatusBarAction() );
//			 //j21.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 //toolBar.add(j21);
//			 
//			 
////			 j20.setBorder(new BevelBorder(BevelBorder.RAISED));
////			 j20.setToolTipText("退出系统");
////			 j20.addActionListener(this);
//
//			 toolBar.addSeparator();
//			 tb_fileExplorer = toolBar.add(new ButtonAction(MainFrame.pic_fileExplorer));
//			 tb_fileExplorer.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_fileExplorer.setToolTipText("File Explorer");
//			 tb_fileExplorer.addActionListener( this );
//			 tb_fileCopy = toolBar.add(new ButtonAction(MainFrame.pic_fileCopy));
//			 tb_fileCopy.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_fileCopy.setToolTipText("File Copy");
//			 tb_fileCopy.addActionListener( this );
//			 tb_favoriteFile = toolBar.add(new ButtonAction(MainFrame.pic_favoriteFile));
//			 tb_favoriteFile.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_favoriteFile.setToolTipText("Favorite File");
//			 tb_favoriteFile.addActionListener( this );
//			 
//			 toolBar.addSeparator();
//			 tb_exitSys = toolBar.add(new ButtonAction(MainFrame.pic_exit));
//			 tb_exitSys.setBorder(new BevelBorder(BevelBorder.RAISED));
//			 tb_exitSys.setToolTipText("退出系统");
//			 tb_exitSys.addActionListener(this);
//			 
//			 toolBar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);
//			 toolBar.setOrientation(JToolBar.HORIZONTAL);
//			 toolBar.addComponentListener(new java.awt.event.ComponentAdapter() {
//			 	public void componentDraged(java.awt.event.ComponentEvent e) {
//			 		// --Warning! System.out.println("componentDraged"); // TODO Auto-generated Event stub componentMoved()
//			 		thisResized(null);
//			 	}
//			 });
//		}
//		
//		return toolBar;
//	}

	/**
	 * 
	 * @param e
	 */
	public void thisResized(java.awt.event.ComponentEvent e){
//		int width=new Double(leftScrollPanel.getParent().getSize().getWidth()).intValue();
//		int height=new Double(leftScrollPanel.getParent().getSize().getHeight()).intValue()-5;	//5=toolBar's height
//		//System.out.println("w="+width+" h="+height);
//
//		// 5=toolBar's height    2=距左右边界宽度     1=组件相互之间的宽度
//		leftScrollPanel.setBounds(new java.awt.Rectangle(2,this.mainFrame.clientTop,150, height) );
//		//centerBar.setBounds(new java.awt.Rectangle(150 +2+1, this.clientTop,4, height) );
//		rightScrollPanel.setBounds(new java.awt.Rectangle(150+2+1 +4,this.mainFrame.clientTop,width -(150+2+1 +4) -2, height));
//
//		
//		leftScrollPanel.setViewportView(getTree());
//		rightScrollPanel.setViewportView(getTable());
	}
	

	//-------------------------------------- copy from web page
    /**   设置表的所有列的列宽
     *   @param   table   要设置的表
     */
   public   static   void   setAllColWidth(javax.swing.JTable   table){
           if(table   !=   null){
                  
                   //如果表为空，则不排序
                   if(table.getRowCount()==0)
                           return;
                  
                   int   colnumber   =   table.getColumnCount();
                   for(int   i=0;i <colnumber;i++){
                           setColWith(table,i);
                   }
           }
   }
  
   /**   设置表的列宽
     *   @param   table   要设置的表
     *   @param   colnumber   列号
     */
   public   static   void   setColWith(javax.swing.JTable   table,int   colnumber){
           TableColumn   mid   =   table.getColumnModel().getColumn(colnumber);
           int   midWidth   =   getPreferredWidthForColumn(table,mid);
           mid.setMinWidth(columnHeaderWidth(table,mid)+5);
           mid.setPreferredWidth(midWidth+5);
   }
  
   /**   取得列的默认宽度
     *   @param   table   表
     *   @param   col   列号
     *   @return   int   列宽
     */
   public   static   int   getPreferredWidthForColumn(javax.swing.JTable   table,TableColumn   col){
           int   hw   =   columnHeaderWidth(table,col);   //header   Width   计算列头宽度
           int   cw   =   widestCellnColumn(table,col);   //column   Width   计算列值宽
           return     hw> cw?hw:cw;
   }
  
  
   /**   取得表头的宽度
     *   @param   table   表
     *   @param   col   列号
     *   @return   int   列宽
     */
   public     static   int   columnHeaderWidth(javax.swing.JTable   table,TableColumn   col){
           TableCellRenderer   renderer   =   col.getHeaderRenderer();
          
           if(renderer   ==   null)
                   return   col.getWidth();
          
           Component   comp   =   renderer.getTableCellRendererComponent(table,col.getHeaderValue(),false,false,0,0);
           return   comp.getPreferredSize().width;
          
   }
   /**   取得表单元的宽度
     *   @param   table   表
     *   @param   col   列号
     *   @return   int   列宽
     */
   private     static   int   widestCellnColumn(javax.swing.JTable   table,TableColumn   col){
           int   c   =   col.getModelIndex();
           int   width=0;
           int   maxw   =   0;
          
           for(int   r=0;   r <table.getRowCount();   r++){
                   TableCellRenderer   renderer   =   table.getCellRenderer(r,c);
                   Component   comp   =   renderer.getTableCellRendererComponent(table,table.getValueAt(r,c),false,false,r,c);
                   width   =   comp.getPreferredSize().width;
                   maxw   =   width> maxw?width:maxw;
           }
           return   maxw;
          
   } 
	//-------------------------------------- copy from web page end
   
   


//	 /**
//	  * 
//	  *
//	  */
//	 private void executeFileCopy() {
////		 FileCopyDialog fc = new FileCopyDialog(this);
////		 ComponentUtil.setLocationToCenter(this,fc);
////		 fc.setVisible( true );
//		 getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_FileMasterMainPanel_Index );	
//		 getFileMasterMainPanel().setCurrentTabIndex( FileMasterMainPanel.MainTabPane_FileCopy_Index );	
//			
//	} 

//	/**
//	 *
//	 */
//	public void removeAwoke(int id){
//		this.getReminderMainPanel().removeAwoke(id );
//	}
//	

		/**
		 * 退出系统
		 *
		 */
		 public void executeExitSystem() {		 
			 if( this.executeSaveCheck() ){
				 System.exit(0);
			 }
			 
		 }

	/**
	  * execute saveCheck before exit from system.
	  * @return
	  */
 private boolean executeSaveCheck() {
		 int iop=JOptionPane.showConfirmDialog(this, this.msgDialog_exitFromSystem, this.msgDialog_info,
				 JOptionPane.CANCEL_OPTION,
				 JOptionPane.QUESTION_MESSAGE);
		 //保存到数据库中
		 if(iop==JOptionPane.YES_OPTION) {
//						 this.doSave();
			 return true;
		 } else if(iop==JOptionPane.NO_OPTION){ 
			 return true;
 		 } else{
			 return false;
 		 }
	 }
		 
	/**
	 * implements ActionListener, call Local execute... method.
	 * 
	 * 全部调用外部方法，以免重复实现某项功能。
	 */
	public void actionPerformed(ActionEvent event) {
		
	}

	DirectorPanel currentPanel = null;
	private String appIconTitle;
	/**
	 * 执行改变语言命令
	 * @param type
	 */
	public void executeChangeLanguage(Locale locale) {

		//System.setProperty(MainFrame.DIRECTOR_LANGUAGE, type);
		
		Locale.setDefault( locale );
		languageManager.setLanguage( locale );
		
		if (currentPanel!=null) {
			currentPanel.refreshView();
		}
	}

	 /**
	  * 监听语言改变
	  */
	public void update(Observable o, Object arg) {
		super.update(o, arg);
		
		//System.out.println(Locale.getDefault());
		ResourceBundle bundle = I18nUtils.getBundle(DirectorConstants.I18n_Language_Name);
		
		// Windows	    
		this.setTitle( I18nUtil.getBundleString(bundle, MainFrame.class, "application.Title") ); //bundle.getString("application.Title") );		
		
		mainTabPane.setTitleAt(MainTabPane_ReminderMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.reminderMainPanel.Text"));
		mainTabPane.setTitleAt(MainTabPane_CalendarMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.calendarMainPanel.Text"));
		mainTabPane.setTitleAt(MainTabPane_ResourceMasterMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.resourceMasterMainPanel.Text"));
		mainTabPane.setTitleAt(MainTabPane_LocalSearchMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.localSearchMainPanel.Text"));
		mainTabPane.setTitleAt(MainTabPane_NoteBookMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.noteBookMainPanel.Text"));
		mainTabPane.setTitleAt(MainTabPane_NotePaperMainPanel_Index,
				I18nUtil.getBundleString(bundle, MainFrame.class, "tab.notePaperMainPanel.Text"));

		MainPanel_Codes[0][1]=I18nUtil.getBundleString(bundle, MainFrame.class, "tab.reminderMainPanel.Text");
		MainPanel_Codes[1][1]=I18nUtil.getBundleString(bundle, MainFrame.class, "tab.calendarMainPanel.Text");
		MainPanel_Codes[2][1]=I18nUtil.getBundleString(bundle, ResourceMasterMainPanel.class, "tab.FileExplorer.Text");
		MainPanel_Codes[3][1]=I18nUtil.getBundleString(bundle, ResourceMasterMainPanel.class, "tab.FileCopy.Text");
		MainPanel_Codes[4][1]=I18nUtil.getBundleString(bundle, ResourceMasterMainPanel.class, "tab.FavoriteFiles.Text");
		MainPanel_Codes[5][1]=I18nUtil.getBundleString(bundle, ResourceMasterMainPanel.class, "tab.DocumentLibrary.Text");
		MainPanel_Codes[6][1]=I18nUtil.getBundleString(bundle, ResourceMasterMainPanel.class, "tab.ProgramLibrary.Text");
		MainPanel_Codes[7][1]=I18nUtil.getBundleString(bundle, MainFrame.class, "tab.localSearchMainPanel.Text");
		MainPanel_Codes[8][1]=I18nUtil.getBundleString(bundle, MainFrame.class, "tab.notePaperMainPanel.Text");
		///((DirectorMenuBar)this.getJMenuBar()).update( o, arg );
	    ///this.getReminderMainPanel().update( o, arg );
		
		appIconTitle = I18nUtil.getBundleString(bundle, MainFrame.class, "application.IconTitle");
		
		if (trayIcon!=null) {
			updateTrayIconToolTip(trayIcon);
		}
		
	}

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        //java.net.URL imgURL = MainFrame.class.getResource(path);
    	String imgURL = path;
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

//	/**
//	  * innerClass
//	  */
//	 class ButtonAction extends AbstractAction  {
//		 public ButtonAction(String str) {
//			 super(null,new ImageIcon(str));
//		 }
//		 public void actionPerformed(ActionEvent e) {
//		 }
//	 }

	public void mouseClicked(MouseEvent e) {
		Object eventObj = e.getSource();
		if (eventObj==trayIcon) {  //change tooltip for trayIcon, add to mouseEntered(not supported) is better.
			updateTrayIconToolTip(trayIcon);
		}
       if( eventObj==trayIcon 
    		   && !SwingUtilities.isRightMouseButton(e)){  //击鼠标右键这里不处理 e.getClickCount()==2
       	   //System.out.println("111");
           //showIT(true);   
//       		this.setExtendedState(NORMAL);
 	       this.setVisible(true);  //must before call setExtendedState
           this.setExtendedState( JFrame.NORMAL);

       }
	}

	/**
	 * jdk6 : 除了public void mouseEntered（MouseEvent e）和public void mouseExited（MouseEvent e）不被支持
	 */
	public void mouseEntered(MouseEvent e) {
		log.info("Tray icon: Mouse entered");
		Object eventObj = e.getSource();
	       if( eventObj==trayIcon ){   
	    	   StringBuffer toolTip = new StringBuffer();
	    	   toolTip.append("System Direcotr,Press ["+Main.MainFrame_Shortcut_Key+"] open.");
	    	   trayIcon.setToolTip(toolTip.toString());
	        }
		
	}

	public void mouseExited(MouseEvent e) {
		log.info("Tray Icon - Mouse exited!"); 
		
	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public DirectorPanel getCurrentPanel() {
		return currentPanel;
	}

	public void setCurrentPanel(DirectorPanel currentPanel) {
		this.currentPanel = currentPanel;
	}

//	    public class RightAction extends AbstractAction {
//	        public RightAction(String text, ImageIcon icon,
//	                           String desc, Integer mnemonic) {
//	            super(text, icon);
//	            putValue(SHORT_DESCRIPTION, desc);
//	            putValue(MNEMONIC_KEY, mnemonic);
//	        }
//	        public void actionPerformed(ActionEvent e) {
//	            displayResult("Action for third button/menu item", e);
//	        }
//	    }
	
	/**
	 * 统一处理不同地方的同一功能，达到所有的都同步。
	 * @param isOpenNoDisturb
	 */
	public void setOpenNoDisturbState(boolean isOpenNoDisturb){
		Main.isNoDisturbOpen = !Main.isNoDisturbOpen;
		this.getReminderMainPanel().getMenuBar().jmi_Tool_OpenNoDisturb.setSelected(Main.isNoDisturbOpen);
		this.trayPopupMenu.tray_Menu_OpenNoDisturb.setState(Main.isNoDisturbOpen);
	}

	private static MainFrame instance = null;
	public static MainFrame getInstance() {
		if (instance==null) {
			instance = new MainFrame();
		}
		return instance;
	}
	
	// create a new one for restart
	public static MainFrame createNewInstance() {
		instance = new MainFrame();
		return instance;
	}

	// -W:公共调用入口
	public void executeLocalSearch() {
		executeLocalSearch(null);
	}
	
	public void executeLocalSearch(String kw) {
		this.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_LocalSearchMainPanel_Index );	
		this.getLocalSearchMainPanel().getKeywordTextField().requestFocusInWindow();
		if (kw!=null) {
			this.getLocalSearchMainPanel().getKeywordTextField().setText(kw);
	    }
	}
	 
}
